import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import router from '@/router/index'
import { SSO_LOGIN } from '@/config/loginConfig'
import * as BASE_URL from '@/config/baseUrl'
let isExpired = false

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
var baseURL = process.env.VUE_APP_BASE_API;

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: baseURL,
  // 超时
  timeout: 100000
})
service.baseURL = baseURL
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 如若接口定义中自定义配置了Authorization，则不再重新设置；接口中没有定义的统一使用eam获取的token
  if (!config.headers.Authorization) {
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
  }
  // 每个请求添加请求来源，pc/app，菜单路由
  config.headers['Common-Channel-Id'] = store?.getters?.device == "desktop" ? 'WEB_PC' : "WEB_APP"
  config.headers['Common-Module-Router'] = router.app?._route?.path || ''
  config.headers['Common-Module-Router-Name'] = encodeURI(router.app?._route?.meta?.title) || ''

  // 没有配置请求服务的，统一都为process.env.VUE_APP_BASE_API + BASE_URL.ADMIN服务(历史遗留问题，有很多写在业务代码中的请求)
  const servers = Object.values(BASE_URL).filter(ele => typeof ele === 'string').join('/|')
  const exp = new RegExp(`^${servers}/`)
  const flag = exp.test(config.url)
  if (!flag) {
    config.baseURL = process.env.VUE_APP_BASE_API + BASE_URL.ADMIN
  }

  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof(value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
  console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  const dataType = Object.prototype.toString.call(res.data);
  if (["[object ArrayBuffer]", "[object Blob]"].includes(dataType)) {
    const name =
      res.headers["content-disposition"]?.match(
        /(?<=filename=).+/g
      ) || '';
    return {
      file: res.data,
      name: name ? name[0] : ''
    };
  }
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    if (code != 200){
      var loadings = document.getElementsByClassName('el-loading-mask');
      if (loadings.length > 0){
        for (let i = loadings.length - 1;i > 0;i--){
          loadings[i].remove()
        }
      }
    }
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
      handleExpiredLogin()
    }
    else if (code === 402) {
     Message({
        message: '您已经在其他地点登录，请重新登录',
        type: 'warning'
      })
      store.dispatch('FedLogOut').then(() => {
        if(SSO_LOGIN){
          router.push({path:'/'})
        } else {
          router.push({path:'/login'})
        }
      })
    }
    else if (code === 500) {
      // 判断是否要隐藏message
      if (res.config?.hideErrorMessage != true) {
        Message({
          message: msg,
          type: 'error'
        })
      }
      return Promise.reject(new Error(msg))
    }
    else if (code === 550) {
      Message({
        message: msg,
        type: 'warning'
      })
      return Promise.reject(new Error(msg))
    }
    else if (code === 416){
      Message({
        message: msg,
        type: 'warning'
      })
      return Promise.reject('error')
    }
    else if (code == 404 || code == 502){
      Message({
        message: "系统升级中,请稍后再试",
        type: 'warning'
      })
      return Promise.reject('error')
    }
    else if (code != 200) {
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
  //console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "网络异常,请稍后再试";
    }
    else if (message.includes("timeout") || message.includes("Time-out")) {
      message = "系统响应超时,请稍后再试";
    }
    else if (message.includes("504")) {
      message = "系统响应超时,请稍后再试";
    }
    else if (message.includes("502")) {
      message = "系统升级中,请稍后再试";
    }
    else if (message.includes("404")) {
      message = "系统升级中,请稍后再试";
    }
    else if (message.includes("401")) {
      handleExpiredLogin()
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 重新登陆的跳转
function handleExpiredLogin() {
  if (!isExpired) {
    isExpired = true
    MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      store.dispatch('FedLogOut').then(() => {
        if(SSO_LOGIN){
          router.push({path:'/'})
        } else {
          router.push({path:'/login'})
        }
        isExpired = false
      })
    }).catch(() => {
      store.dispatch('FedLogOut').then(() => {
        if(SSO_LOGIN){
          router.push({path:'/'})
        } else {
          router.push({path:'/login'})
        }
        isExpired = false
      })
    });
  }
}

export default service
